library(dplyr)
library(haven)
library(tidyverse)
library(car)
library(survey)
library(anesrake)
library(kableExtra)

sink("../output/voteredo2022_build_analysis.log")

# run and prep 2020 voteredo

source("voteredo2020_build.R")
print("Weights recomputed for 2020")
# Bring in data
dat22 <- read.csv("../input/ces_2022_weighted_final.csv")
source <- read.csv("../input/CCES22_OUTPUT_sourcevar.csv")

dat22 <- merge(dat22, source, all.x=T, by="caseid")

# Inconsistent tag
dat22$inconsistent <- 0
dat22$inconsistent[dat22$CC22_334c==1 & dat22$CC22_334d==1] <- 1

# Panel source
dat22$source <- "Off Panel"
dat22$source[dat22$add_confirm>0] <- "YouGov Panel"

# Create a variable identifying partisans (and leaners)
dat22$party[dat22$pid7<4] <- "Democrats"
dat22$party[dat22$pid7>4 & dat22$pid7<8] <- "Republicans"
dat22$party <- as.factor(dat22$party)

# Recode vote preference variable so that there is one variable for whether or not respondent is voting for a House Dem and another for whether or not respondent is voting for a House Rep
dat22$HouseDemocrat <- 0
dat22$HouseDemocrat[dat22$CC22_367_voted==1 & dat22$HouseCand1Party=="Democratic"] <- 1
dat22$HouseDemocrat[dat22$CC22_367==1 & dat22$HouseCand1Party=="Democratic"] <- 1
dat22$HouseDemocrat[dat22$CC22_367_voted==2 & dat22$HouseCand2Party=="Democratic"] <- 1
dat22$HouseDemocrat[dat22$CC22_367==2 & dat22$HouseCand2Party=="Democratic"] <- 1
dat22$HouseDemocrat[dat22$CC22_367_voted==3 & dat22$HouseCand3Party=="Democratic"] <- 1
dat22$HouseDemocrat[dat22$CC22_367==3 & dat22$HouseCand3Party=="Democratic"] <- 1
dat22$HouseDemocrat[dat22$CC22_367_voted==4 & dat22$HouseCand4Party=="Democratic"] <- 1
dat22$HouseDemocrat[dat22$CC22_367==4 & dat22$HouseCand4Party=="Democratic"] <- 1
dat22$HouseDemocrat[dat22$CC22_367_voted==6 & dat22$HouseCand6Party=="Democratic"] <- 1
dat22$HouseDemocrat[dat22$CC22_367==6 & dat22$HouseCand6Party=="Democratic"] <- 1
dat22$HouseDemocrat[dat22$CC22_367==99 | dat22$CC22_367_voted==99] <- NA

dat22$HouseRepublican <- 0
dat22$HouseRepublican[dat22$CC22_367_voted==2 & dat22$HouseCand2Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367==2 & dat22$HouseCand2Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367_voted==3 & dat22$HouseCand3Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367==3 & dat22$HouseCand3Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367_voted==4 & dat22$HouseCand4Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367==4 & dat22$HouseCand4Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367_voted==5 & dat22$HouseCand5Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367==5 & dat22$HouseCand5Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367_voted==6 & dat22$HouseCand6Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367==6 & dat22$HouseCand6Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367_voted==7 & dat22$HouseCand7Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367==7 & dat22$HouseCand7Party=="Republican"] <- 1
dat22$HouseRepublican[dat22$CC22_367==99 | dat22$CC22_367_voted==99] <- NA

dat22$Trump <- car::recode(dat22$presvote20post, "1=0; 2=1; 3:5=0")
dat22$Trump[dat22$presvote20post==6] <- NA
dat22$Biden <- car::recode(dat22$presvote20post, "1=1; 2=0; 3:5=0")
dat22$Biden[dat22$presvote20post==6] <- NA
# Create lvweight
dat22$lvweight <- dat22$nationalweight*dat22$Voted

#### Re-weight without the inconsistents ####

dat2 <- subset(dat22, inconsistent==0)

# Create list of population targets based on 2020 5-year ACS
gender <- c(0.49, 0.51)
agecat <- c(0.21, 0.17, 0.16, 0.17, 0.15, 0.14)
race5 <- c(0.63, 0.12, 0.16, 0.06, 0.03)
educ <- c(0.12, 0.27, 0.22, 0.08, 0.19, 0.11)
weduc <- c(0.05, 0.17, 0.14, 0.06, 0.14, 0.08, 0.07, 0.10, 0.08, 0.03, 0.06, 0.03)
region <- c(0.18, 0.21, 0.38, 0.24)
prez20 <- c(0.342, 0.312, 0.013, .333)
ownhome2 <- c(.658, .342)

targets <- list(gender, agecat, race5, educ, weduc, prez20, ownhome2, region)
names(targets) <- c("gender", "agecat",  "race5", "educ", "weduc", "prez20", "ownhome2", "region")

outsave <- anesrake(targets, dat2, caseid = dat2$caseid
                    , cap = 8, type = "nolim")
dat2$nationalweight2  <- unlist(outsave[1])
print("Weights recomputed for 2022")
dat2$lvweight2 <- dat2$nationalweight2 * dat2$Voted

#### Recompute house vote and merge with 2020 results for table ####
print("Reweighted house vote, 2022")
noc_22 <- dat2 %>%
  summarise(Democrat = round(weighted.mean(HouseDemocrat*100, lvweight2, na.rm=TRUE),1),
            Republican = round(weighted.mean(HouseRepublican*100, lvweight2, na.rm=TRUE),1))
print("Original house vote, 2022")
full_22 <-dat22 %>%
  summarise(Democrat = round(weighted.mean(HouseDemocrat*100, lvweight, na.rm=TRUE),1),
            Republican = round(weighted.mean(HouseRepublican*100, lvweight, na.rm=TRUE),1))

combined_22 <- full_22 %>% rbind(noc_22)
combined_22$Restriction <- "Full Sample"
combined_22$Restriction[2] <- "Contradictors Removed"
combined_22 <- combined_22 %>% select(Restriction, Democrat, Republican)
combined_both <- combined_22 %>% cbind(combined_20)

combined_output <- combined_both %>%
  kbl(booktabs = TRUE,
      align = c("r", rep("c", 4)),
      format = "latex",
      linesep = "",
      col.names = c("Restriction", "Democrat Vote", "Republican Vote", "Democrat Vote", "Republican Vote")) |>
  add_header_above(c(" " = 1, "2022" = 2, "2020" = 2)) |>
  row_spec(6, hline_after = TRUE)

combined_output %>%
  write_lines("../output/house_vote.tex")
print("Table B1 created")
#### Recompute presidential vote and merge with 2020 results for table ####
print("Reweighted trump vote, 2022")
noc_22_trump <- dat2 %>%
  summarise(Biden = round(weighted.mean(Biden*100, lvweight2, na.rm=TRUE),1),
            Trump = round(weighted.mean(Trump*100, lvweight2, na.rm=TRUE),1))
print("Original trump vote, 2022")
full_22_trump <-dat22 %>%
  summarise(Biden = round(weighted.mean(Biden*100, lvweight, na.rm=TRUE),1),
            Trump = round(weighted.mean(Trump*100, lvweight, na.rm=TRUE),1))

combined_22_trump <- full_22_trump %>% rbind(noc_22_trump)
combined_22_trump$Restriction <- "Full Sample"
combined_22_trump$Restriction[2] <- "Contradictors Removed"
combined_22_trump <- combined_22_trump %>% select(Restriction, Biden, Trump)
combined_both_trump <- combined_22_trump %>% cbind(combined_20_trump)

combined_output_trump <- combined_both_trump %>%
  kbl(booktabs = TRUE,
      align = c("r", rep("c", 4)),
      format = "latex",
      linesep = "",
      col.names = c("Restriction", "Biden Vote", "Trump Vote", "Biden Vote", "Trump Vote")) |>
  add_header_above(c(" " = 1, "2022" = 2, "2020" = 2)) |>
  row_spec(6, hline_after = TRUE)

combined_output_trump %>%
  write_lines("../output/pres_vote.tex")
print("Table B2 Produced")




